import socket,sys,traceback
import time
from p import test  
port =  50000
host = ''

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((host,port))
s.listen(10	)

sign_p = 0
header_p = "pict"
header_t = "text"

while True:
	#clientsock.settimeout(5)
	try :
		while True:
			#data = clientsock.recv(4096)
			#if data:
			#	print data
			
			clientsock ,clientaddr = s.accept()
			print "Got connection from ",clientsock.getpeername()
			mes = raw_input("some here>> ")
			if (mes == "p"):
				sign_p =1

			if (sign_p == 0):
				Message = header_t + "%8d"%len(mes) + mes
				byte = Message.encode('utf-8')
				print Message
				name = time.ctime() + "from Qingluan!\n"
				#if not len(name):
				#	break
				clientsock.sendall(byte)
		
			#file1 = open("/Users/darkh/Desktop/some.tar.gz","rb")
			if (sign_p ==1 ):
				pic = test()
				buf = pic.get()
				
				size = len(buf)
				Message_header = header_p + "%8d"% size 
				byte = Message_header.encode("utf-8")
				byte = byte + buf
				print "picture len : ",size
				print Message_header
				clientsock.sendall (byte)
				print "send picture ... ok"
				sign_p = 0
			#string2 = ""
			#for lines in file1:
			#	string2 += lines
			#des = ".pdf"
			#time.sleep(2)
			#clientsock.sendall(string2)
			
			clientsock.close()
	except socket.timeout:
		print " connection may close"
		#sys.exit(0)
	except (KeyboardInterrupt,SystemExit):
		raise
	except:
		traceback.print_exc()

	try :
		clientsock.close()
    	except KeyboardInterrupt :
		raise
	except :
		traceback.print_exc()

	try : 
		clientsock.close()
	except KeyboardInterrupt:
		raise
	except:
		traceback.print_exc()
	
